package com.tanhua.dubbo.mongo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Visitors visitors) {
        //一天只能添加一回数据
        //判断条件
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorsId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());

        boolean exists = mongoTemplate.exists(Query.query(criteria), Visitors.class);
        if (!exists){
            mongoTemplate.save(visitors);
        }

    }

    //根据被访问者id 查询 访问者  只返回5个数据
    public List<Visitors> findById(Long userId,Long date) {

        Criteria criteria = Criteria.where("userId").is(userId)
                  .and("date").gt(date);

        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("date"))).limit(5);

        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    // 谁看过我 - 翻页列表
    public List<Visitors> finByfriends(Integer page, Integer pagesize, Long userId) {

        Criteria criteria = Criteria.where("userId").is(userId);

        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize).limit(pagesize);

        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);

        return visitors;
    }
}
